
Page({
    data: {
		list:[],
		
		defaultList:[],
		red2:[],
		
		prize:0,

		page:1,
		loadEnd:false,
		
		isShowAdd:false,
		selList:[]
    },
    async onLoad (options) {
        this.data.openID = await getOpenId()
		
        await this.getPeriodWinData();

		this.loadmore();

		// this.getAllList([2,9,25,22,31,32],[2,6])

    },
	loadmore(){
		if( this.data.loadEnd ) return;
		let data = this.setPaginate(this.data.defaultList,10,this.data.page);
		if( !data||!data.length ){
			this.data.loadEnd = true;
			this.setData({ loadEnd:this.data.loadEnd })
			return
		}

		let list = this.data.list;
		list = list.concat(data);
		this.data.page++;
		this.data.list = list;
		this.setData({ list:this.data.list })
	},
	// 设计分页
	setPaginate(list,size,page){
		let start = ( page-1 )*size;
		let end = page*size;
		return list.slice(start,end)
	},

	close(){
		this.setData({ isShowAdd:false })
	},
	// 添加一直
	add(e){
		this.setData({
			isShowAdd:true,
			selList:[]
		})
	},
	selectClick(e){
		let { item,type } = e.currentTarget.dataset;
		let list = this.data.selList;
		list.push({num:item,type:type})
		list = [].concat(list.filter(item=>item.type==1),list.filter(item=>item.type==2))
		this.data.selList = list;

		this.setData({
			selList:this.data.selList,
		})
	},
	openShow(e){
		let { item } = e.currentTarget.dataset;
		console.log("item",item)
		let list = this.getAllList(item.filter(e=>e.type==1).map(e=>e.num),item.filter(e=>e.type==2).map(e=>e.num))
		console.log(list)
	},
	getAllList (num1,num2){
		function getCombinations(numbers, targetCount) {
			// 存储所有组合的数组
			const combinations = [];
			// 递归函数，用于生成组合
			function generateCombinations(currentCombo, remainingNumbers) {
			  // 当组合中的数字数量达到目标数量时，将其添加到结果数组中
			  if (currentCombo.length === targetCount) {
				combinations.push(currentCombo.slice()); // 使用slice()创建数组副本，因为push会改变数组
				return;
			  }
			  // 遍历剩余的数字
			  for (let i = 0; i < remainingNumbers.length; i++) {
				// 将当前数字添加到组合中
				currentCombo.push(remainingNumbers[i]);
				// 递归调用，继续生成剩余数字的组合
				generateCombinations(currentCombo, remainingNumbers.slice(i + 1));
				// 回溯，移除当前数字以尝试其他组合
				currentCombo.pop();
			  }
			}
			// 调用递归函数，从空组合和所有数字开始
			generateCombinations([], numbers);
			// 返回所有组合
			return combinations;
		}
		console.log(num1,num2)
		let result = [];
		let combos = getCombinations(num1, 6);
		console.log(combos)
		// for(let i=0;i<num2.length;i++){
		// 	console.log('combos',num2[i],combos)
		// 	combos.forEach(item=>{
		// 		result.push(item.push(num2[i]))
		// 	})
		// }
		console.log(result)
		return result;
	},
	submitClick(){
		let defaultList = this.data.defaultList;
		let selList = this.data.selList;

		let code = this.data.code + 1;
		if( defaultList.some(e=>e.period==code) ){
			defaultList = defaultList.map(item=>{
				item.period = Number(item.period);
				if( item.period==code ){
					let list = item.list;
					list = [].concat(list,[selList])
					item.list = list;
				}
				return item;
			})
		}else{
			defaultList.unshift({
				period: code,
				day:common.moment().format("YYYY-MM-DD"),
				list:[selList],
				win_code:[]
			})
		}
		console.log('defaultList',defaultList)
		writeFile(defaultList,"2ball")

		this.setData({
			isShowAdd:false,
			defaultList:defaultList
		})
		this.data.page = 1;
		this.data.loadEnd = false;

		this.loadmore();
	},
	async getPeriodWinData(){
		return new Promise(async (resolve,reject)=>{
			let defaultList = await request("2ball");
			let { code,data,red2 } = await this.getDay();
			this.setData({ code,data,red2 })

			// // 是否需要更新
			// if( !defaultList.some(item=>item.code==code) ){
			// 	defaultList.unshift({ code,data,red2 });
			// 	writeFile(defaultList,"2ball")
			// }

			console.log(defaultList)

			this.data.defaultList = defaultList;
			this.data.prize = defaultList.filter(item=>item.isBuy).length*10

			this.setData({ defaultList:this.data.defaultList,prize:this.data.prize });

			this.getList();
			resolve();
		})
	},
    getList(){
        let list = this.data.defaultList;
		return new Promise((resolve,reject)=>{
			wx.request({
				url: 'https://www.yidingniu.net.cn/weapp/openDetail/5.html',
				dataType:"其他",
				responseType:"text",
				enableHttp2:true,
				complete:(res=>{
					let result = JSON.parse(res.data);
                    let isChange = false;
                    (result||[]).forEach(item => {
                        if( !list.some(e=>e.period==Number(item.Name))  ){
                            isChange = true;
                            list.push({
                                period:Number(item.Name),
                                openID:this.data.openID,
                                day:common.moment(item.EndTime).format("YYYY-MM-DD"),
                                create_at:common.moment(item.EndTime).format("YYYY-MM-DD HH:MM:SS"),
                                list:[],
                                win_code:item.OpenNumber.replace('+',',').split(',')
                            })
                            list.sort((a,b)=>{
                                return b.period-a.period;
                            })
                        }else{
                            list.forEach(e=>{
                                if( e.period==Number(item.Name) ){
                                    isChange = true;
                                    e.win_code = item.OpenNumber.replace('+',',').split(',')
                                }
                            })
                        }
                    });
                    if( isChange ){
						writeFile(list,"2ball")
                    }
                })
            })
        })
    },
	getDay(){
		return new Promise((resolve,reject)=>{
			wx.request({
				url: 'https://caipiao.ip138.com/shuangseqiu/',
				dataType:"其他",
				responseType:"text",
				enableHttp2:true,
				complete:(res=>{
					let html = res.data.replace(' ','');
					html = html.replace('    ','');
					html = html.replace('                               ','');
					html = html.replace('\n\n','');
					html = html.replace('\n\n','');
					let star = html.indexOf('<span class="period">');
					var period = html.substring(star+21,star+21+7);
					let star2 = html.indexOf('总销售额：<span>');
					var prize = html.substring(Number(star2)+11,Number(star2)+11+11)
					let redball = 'cache.ip138.com/public/image/award/redball-';
					var i1 = html.indexOf(redball);
					var str = html.substr(i1-12,520*3+100)
					str = str.replace(/\/\/cache.ip138.com\/public\/image\/award\/redball-/g,'');
					str = str.replace(/\/\/cache.ip138.com\/public\/image\/award\/blueball-/g,'');
					str = str.replace(/\n/g,'');
					var b=/alt="\d*"/g
					var s=str.match(b)
					let win = []
					for(var i= 0;i<s.length;i++){
						let num = s[i].replace("alt=",'');
						num = num.replace(/"/g,'');
						win.push(num);
					}
					// let data = {
					// 	period:2024004,
					// 	prize:Number(prize),
					// 	win:["2", "16", "18", "29", "27", "8", "9"]
                    // }
					let data = {
						code:Number(period),
						red2:win
                    }
                    console.log("data",data)
					resolve(data)
				})
			})
		})
	}
})